import React, { useMemo, useRef } from "react";
import { Badge } from "antd";

import {ProTable, type TableType, type IProTableRef } from "@yaf/pro-ui";
import { helper } from "@yaf/utils";
import { EnumAuthKey, permission } from "@/service";
import { useThemeToken, getEnv } from "@/constants";

import { getDataAction, getFilterItems } from './proTableDriver';
import { RespDataType } from '../api';
import CreatePost from "./CreatePost";

const List: React.FC = () => {
  const { themeToken } = useThemeToken();
  const proTableRef = useRef<IProTableRef>();
  const columns = useMemo(() => getColumns(), []);

  return <ProTable
    ref={proTableRef}
    dataAction={getDataAction(proTableRef)}
    rowKey={"postId"}
    theme={themeToken.proTableToken}
    headerProps={{
      operatorProps: {
        btnList: [
          { innerType: "create", authKey: EnumAuthKey.sysPost.addButton },
          { innerType: "edit", authKey: EnumAuthKey.sysPost.editButton },
          { innerType: "delete", authKey: EnumAuthKey.sysPost.removeButton }
        ].filter((item) => permission.can(item.authKey)),
        createOrEditProps: {
          modalProps: {
            width: 600
          },
          CreateOrEditContent: CreatePost,
          getModalTitle: (rowKey) => rowKey ? "编辑岗位" : "创建岗位",
        },
      },
      filterProps: {
        maxWidth: "60%",
        filterItems: getFilterItems()
      }
    }}
    contentProps={{
      tableProps: {
        columns,
      }
    }}
    onError={(msg) => console.error(msg)}
  />

}

export default List;

const getColumns = () => {
  const { commonStatusList } = getEnv().globalConfig;
  const statusToInfo = helper.convertArrayToObj(commonStatusList);

  const columns: TableType.ColumnsType<RespDataType.PostItem> = [
    {
      title: '岗位编码',
      dataIndex: 'postCode',
    },
    {
      title: '岗位名称',
      dataIndex: 'postName',
    },
    {
      title: '岗位排序',
      dataIndex: 'postSort',
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: (value) => {
        const { label, color } = statusToInfo[value];
        return <Badge color={color} text={label} />
      }
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
    },
  ];

  return columns;
}
